<?php

// 订单

namespace app\shop\controller;

use think\Db;
use think\Url;
use think\Cache;
use think\Request;
use think\Session;
use think\Response;
use think\Exception;
use think\Controller;
use app\shop\common\GuessGoods;
use app\shop\model\Shop as ShopModel;
use app\shop\model\MemberOrder as MemberOrderModel;
use app\shop\model\MemberRefund as MemberRefundModel;
use app\shop\model\MemberOrderAttached as MemberOrderAttachedModel;

class MemberOrder extends Controller
{

    /**
     * 我的订单
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        // 获取参数

        $inquire = $request->param();
        $memberId = Session::get('member_id');

        // 搜索条件
        $condition['member_id'] = ['eq', $memberId];

        // 条件
        if (empty($inquire['status'])) $inquire['status'] = 'all';
        if ($inquire['status'] <> 'all') $condition['status'] = ['in', $inquire['status']];
        if ($inquire['status'] == 'w') $condition['status'] = ['eq', 0];
        if ($inquire['status'] == 'all') $condition['status'] = ['neq', 5];
        if (!empty($inquire['title'])) $condition['member_order_attached.title|member_order.shop_order_number|shop.title'] = ['like', '%' . $inquire['title'] . '%'];

        $result = Db::view('member_order', 'id,member_id,shop_id,shop_order_number,price,status,create_time,address_name,order_number,way')
            ->view('member_order_attached', 'order_id,goods_id,title,thumb_img,number,id as aid,status as attached_status,price as goods_price,attr,rebate_percentage', 'member_order.id = member_order_attached.order_id')
            ->view('shop', 'member_id as user_id,title as shop_title', 'shop.member_id = member_order.shop_id')
            ->where($condition)->order(['id' => 'desc'])->paginate(5, false, ['query' => $inquire]);



        // 猜你喜欢
        $guess_like = (new GuessGoods)->guessLike();


        return $this->fetch('', [
            'mate_head'  => '我的订单',
            'result'     => $result,
            'guess_like' => $guess_like,
        ]);

    }


    public function auction()
    {
        $memberId = Session::get('member_id');

        $result = Db::view('auction_order','*')->where('member_id',$memberId)->select();


        $guess_like = (new GuessGoods)->guessLike();

        return $this->fetch('', [
            'mate_head'  => '我的订单',
            'result'     => $result,
            'guess_like' => $guess_like,
        ]);

    }





    /**
     * 取消订单
     * @param Request $request
     * @param MemberOrderModel $memberOrder
     * @return array
     * @throws Exception
     */
    public function order_cancel(Request $request, MemberOrderModel $memberOrder)
    {

        // 获取参数
        $shop_id = Session::get('member_id');
        $order_id = $request->param('order_id');
        $order_number = $memberOrder->where(['id' => $order_id])->value('shop_order_number');

        if (empty($shop_id) || empty($order_number)) throw new Exception('not Empty');

        // 启动事务
        Db::startTrans();

        try {

            // 改变订单状态
            Db::name('member_order')->where(['shop_order_number' => $order_number])->update(['status' => '5']);

            // 读取特价商品
            $limited = Db::name('member_order_attached')->where(['shop_order_number' => $order_number, 'limited_status' => '1'])->field('number,goods_id')->select();

            // 特价商品更改回数量
            if (!empty($limited)) {
                foreach ($limited as $value) {

                    Db::name('limited')->where(['goods_id' => $value['goods_id']])->setDec('purchase_number', $value['number']);

                }
            }

            // 库存返回
            $stock = Db::name('member_order_attached')->where('shop_order_number', $order_number)->find();
            // 主库存
            Db::name('shop_goods')->where('id', $stock['goods_id'])->setInc('inventory', $stock['number']);
            // 分库存
            if (!empty($stock['attr'])) {

                Db::name('shop_spec_attr')->where(['goods_id' => $stock['goods_id'], 'attribute' => $stock['attr']])->setInc('inventory', $stock['number']);
            }

            // 读取价格
            $brokerage = Db::name('member_distribution_order')->where(['order_number' => $order_number])->value('brokerage');

            // 更改金额参数
            Db::name('member_brokerage')->where(['member_id' => $shop_id])->setDec('to_yield', $brokerage);

            // 删除分销订单
            Db::name('member_distribution_order')->where(['distribution_id' => $shop_id, 'order_number' => $order_number])->delete();

            // 提交事务
            Db::commit();

            return ['code' => 200, 'message' => '成功'];

        } catch (\Exception $e) {
            halt($e->getMessage());
            // 回滚事务
            Db::rollback();

            return ['code' => 401, 'message' => '网络繁忙'];
        }
    }


    /**
     * 确认收货
     * @param Request $request
     * @param MemberOrderModel $memberOrder
     * @return array
     * @throws Exception
     */
    public function order_confirm(Request $request, MemberOrderModel $memberOrder)
    {

        if (!$request->isPost()) return ['code' => 400, 'message' => '请求方式错误'];

        // 获取参数
        $user_id = Session::get('member_id');

        $order_id = $request->param('order_id');
        $order_number = $memberOrder->where(['id' => $order_id])->value('shop_order_number');

        if (empty($user_id) || empty($order_number)) throw new Exception('not Empty');

        // 启动事务
        Db::startTrans();
        try {

            // 更改订单状态
            Db::name('member_order')->where(['shop_order_number' => $order_number, 'member_id' => $user_id])->update(['status' => '3']);


            // 更改金额参数
            $this->receivingBrokerage($user_id, $order_number);

            // 提交事务
            Db::commit();


            return ['code' => 200, 'message' => '确认收货成功'];

        } catch (\Exception $e) {
            // halt($e->getMessage());
            // 回滚事务
            Db::rollback();

            return ['code' => 401, 'message' => '网络繁忙'];
        }
    }


    /**
     * 订单详情
     * @param Request $request
     * @param MemberOrderModel $memberOrder
     * @param ShopModel $shop
     * @param MemberOrderAttachedModel $memberOrderAttached
     * @return mixed
     */
    public function detail(Request $request, MemberOrderModel $memberOrder, ShopModel $shop, MemberOrderAttachedModel $memberOrderAttached)
    {
        $orderId = $request->param('order_id');

        $result = $memberOrder->where(['id' => $orderId])->field('create_time,shop_id,create_time,shop_order_number,pay_time,express_number,express_name,express_value,address_name,address_phone,address_area,address_site,price,status,freight,coupon_price,red_packet_price')->find();
        if (!empty($result['pay_time'])) {
            $result['pay_time'] = date('Y-m-d H:i:s', $result['pay_time']);
        } else {
            $result['pay_time'] = "";
        }


        // 店铺名称
        $result['shop_title'] = $shop->where(['member_id' => $result['shop_id']])->value('title');

        $result['goods'] = $memberOrderAttached->where(['shop_order_number' => $result['shop_order_number']])->field('goods_id,attr,number,price,title,thumb_img,rebate_percentage')->select();

        // 物流信息
        $delivery = '';
        if ($result['status'] > 1) {
            $action = self::expressView($result['express_number'], $result['express_value']);

            // 订单流程 显示的出货时间
            if ($action['code'] == 200) {

                $delivery = $action['data']['data'][0]['time'];
                $logistics = $action['data'];
            } else {
                $logistics['data'] = '';
            }
        } else {
            $logistics['data'] = '';
        }


        return $this->fetch('', [
            'mate_head' => '订单详情',
            'data'      => $result,
            'logistics' => $logistics,
            'delivery'  => $delivery,
        ]);
    }


    /**
     * 物流查询
     */
    public function logistics()
    {
        // 获取参数
        $order_id = Request::instance()->param('order_id');

        $result = (new MemberOrderModel())->where('id', $order_id)->field('express_name,express_number,status,express_value')->find();

        // 物流信息
        $delivery = '';
        if ($result['status'] > 1) {
            $action = self::expressView($result['express_number'], $result['express_value']);

            // 订单流程 显示的出货时间
            if ($action['code'] == 200) {

                $delivery = $action['data']['data'][0]['time'];
                $logistics = $action['data'];
            } else {
                $logistics['data'] = '';
            }
        } else {
            $logistics['data'] = '';
        }


        return $this->fetch('', [
            'mate_head' => '物流查询',
            'delivery'  => $delivery,
            'logistics' => $logistics
        ]);
    }


    /**
     * 物流查询
     * @param $express_number
     * @param $express_value
     * @return array
     */
    public function expressView($express_number, $express_value)
    {

        // 修改BUG：订单详情规避空订单
        if (empty($express_value) || empty($express_number)) return ['code'=>401,'data'=>'单号信息错误'];

        // 快递100
        $data['customer'] = Cache::get('web_express_customer');
        $data['param'] = json_encode(['com' => $express_value, 'num' => $express_number]);
        $data["sign"] = strtoupper(md5($data['param'] . Cache::get('web_express_key') . $data['customer']));

        $information = $this->expressPost($data, Cache::get('web_express_url'));

        if ($information['message'] == 'ok') {

            $information['com'] = Db::name('express')->where(['code' => $information['com']])->value('name');

            return ['code' => 200, 'data' => $information];

        } else {

            return ['code' => 402];
        }

    }


    /**
     * 评价商品
     * @param Request $request
     * @param MemberOrderModel $memberOrder
     * @return array
     */
    public function goods_evaluate(Request $request, MemberOrderModel $memberOrder)
    {

        if ($request->isPost()) {

            // 获取参数
            $picArr = $request->param('pic_arr/a', '');

            if ($picArr) {
                $picArr = array_map(function ($item) {
                    $item = ['path' => $item];
                    return $item;
                }, $picArr);
            }

            $orderId = $request->param('order_id');
            $content = $request->param('content');
            $grade = $request->param('grade');
            $goodId = $request->param('good_id');
            $attr = $request->param('attr');
            $title = $request->param('title');
            $thumbImg = $request->param('thumb_img');

            // 订单信息
            $order = $memberOrder->where(['id' => $orderId])->find();
            $data['shop_order_number'] = $order['shop_order_number'];
            $data['shop_id'] = $order['shop_id'];
            $data['goods_id'] = $goodId;
            $data['content'] = $content;
            $data['grade'] = $grade;
            $data['attr'] = $attr;
            $data['title'] = $title;
            $data['thumb_img'] = $thumbImg;

            // 启动事务
            Db::startTrans();

            try {

                // 判断是否提交过
                $find = Db::name('member_order_attached')->where(['goods_id' => $data['goods_id'], 'shop_order_number' => $data['shop_order_number'], 'attr' => $attr, 'status' => '1'])->value('title');

                if (!empty($find)) return ['code' => 402, 'message' => '该商品已评价,请勿重复评价'];

                if (!empty($picArr)) $picArr = serialize($picArr);

                $information = [
                    'member_id'   => Session::get('member_id'),
                    'shop_id'     => $data['shop_id'],
                    'goods_id'    => $data['goods_id'],
                    'content'     => $data['content'],
                    'grade'       => $data['grade'],
                    'title'       => $data['title'],
                    'attr'        => $data['attr'],
                    'thumb_img'   => $data['thumb_img'],
                    'picArr'      => $picArr,
                    'create_time' => time()
                ];

                // 添加到评论表
                Db::name('shop_goods_evaluate')->insert($information);

                // 更改信息
                Db::name('member_order_attached')->where(['goods_id' => $data['goods_id'], 'shop_order_number' => $data['shop_order_number'], 'attr' => $attr, 'status' => '2'])->update(['status' => '1']);

                // 增长评论数
                Db::name('shop_goods')->where(['id' => $data['goods_id']])->setInc('evaluate_number');

                // 送积分
                Db::name('member')->where(['id' => Session::get('member_id')])->setInc('integral', Cache::get('web_integral_evaluate_goods'));

                // 添加记录
                Db::name('integral_record')->insert(
                    [
                        'member_id'   => Session::get('member_id'),
                        'type_id'     => '1',
                        'type'        => '购买',
                        'integral'    => Cache::get('web_integral_evaluate_goods'),
                        'title'       => '评价商品' . $find,
                        'create_time' => time()
                    ]
                );

                // 查询是否还有
                $status = Db::name('member_order_attached')->where(['shop_order_number' => $data['shop_order_number'], 'status' => '2'])->value('id');

                // 更改主表
                if (empty($status)) {
                    Db::name('member_order')->where(['shop_order_number' => $data['shop_order_number'], 'member_id' => Session::get('member_id')])->update(['status' => '4']);
                }

                // 提交事务

                Db::commit();

                return ['code' => 200];

            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙'];
            }
        }

    }


    /**
     * 订单评价
     */
    public function evaluate()
    {
        // 获取用户id 订单ID
        $memberId = Session::get('member_id');
        $orderId = Request::instance()->param('oid', '');
        $aid = Request::instance()->param('aid', '');
        // 抛出异常
        if (empty($memberId) || empty($orderId)) throw new Exception('not Empty');
        // 获取订单信息
        $order = (new MemberOrderModel())->where(['id' => $orderId])->find()->toArray();

        // 订单附属 信息
        $attached = (new MemberOrderAttachedModel())->where(['order_id' => $orderId, 'id' => $aid])->find()->toArray();

        // 抛出异常
        if (empty($order) || empty($attached)) throw new Exception('not Empty');

        $price = $attached['number'] * $attached['price'];

        return $this->fetch('', [
            'mate_head' => '订单评价',
            'order'     => $order,
            'attached'  => $attached,
            'order_id'  => $orderId,
            'aid'       => $aid,
            'price'     => $price
        ]);
    }


    /**
     * 快递100查询
     */
    protected function expressPost($data, $url)
    {
        $o = "";
        foreach ($data as $k => $v) {
            $o .= "$k=" . urlencode($v) . "&";        //默认UTF-8编码格式
        }
        // halt($o);
        $post_data = substr($o, 0, -1);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        //value为0表示直接输出结果
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $is_success = curl_exec($ch);
        curl_close($ch);
        return json_decode($is_success, true);
    }

    /**
     * 收货获得佣金
     * @param $user_id
     * @param $order_number
     */
    protected function receivingBrokerage($user_id, $order_number)
    {

        // 分销返利
        $hierarchy = Db::name('member_distribution')->where(['referrals_id' => $user_id])->order(['level' => 'desc'])->value('hierarchy');

        // 判断是否存在
        if (!empty($hierarchy)) {
            $hierarchy = explode(',', $hierarchy);   // 变成数组
            array_shift($hierarchy);                // 去掉第一个key
            array_pop($hierarchy);                  // 去掉最后一个key
            $hierarchy = array_slice($hierarchy, -3);   // 倒数3个
            rsort($hierarchy);                       // 逆向排序
        }

        // 自己分销佣金
        if (isset($user_id)) {

            // 读取价格
            $brokerage = Db::name('member_distribution_order')
                ->where(['order_number' => $order_number, 'distribution_id' => $user_id])
                ->value('brokerage');

            // 增加佣金 和 总数
            Db::name('member_brokerage')->where('member_id', $user_id)->setDec('to_yield', $brokerage);

            Db::name('member_brokerage')->where('member_id', $user_id)->setInc('actual_amount', $brokerage);
        }

        // 一级分销佣金
        if (isset($hierarchy[0])) {

            // 读取价格
            $brokerage = Db::name('member_distribution_order')
                ->where(['order_number' => $order_number, 'distribution_id' => $hierarchy[0]])
                ->value('brokerage');

            // 增加佣金 和 总数
            Db::name('member_brokerage')->where('member_id', $hierarchy[0])->setDec('to_yield', $brokerage);
            Db::name('member_brokerage')->where('member_id', $hierarchy[0])->setInc('actual_amount', $brokerage);

        }

        // 二级分销佣金
        if (isset($hierarchy[1])) {

            // 读取价格
            $brokerage = Db::name('member_distribution_order')
                ->where(['order_number' => $order_number, 'distribution_id' => $hierarchy[1]])
                ->value('brokerage');

            // 增加佣金 和 总数
            Db::name('member_brokerage')->where('member_id', $hierarchy[1])->setDec('to_yield', $brokerage);
            Db::name('member_brokerage')->where('member_id', $hierarchy[1])->setInc('actual_amount', $brokerage);
        }


    }


    /**
     * 申请订单退款
     */
    public function return_money()
    {
        // 实例化
        $memberOrder = new MemberOrderModel();
        $memberId = Session::get('member_id');

        // 订单号
        $orderId = Request::instance()->param('order');

        // 订单信息
        $order = $memberOrder->where(['id' => $orderId])->field('id,price')->find()->toArray();

        // 我的退换货记录
        $result = Db::view('member_refund', 'order_number,member_id,type,status,amount,create_time')
            ->view('member_order', 'id,shop_id,price as goods_price', 'member_order.shop_order_number = member_refund.order_number')
            ->view('member_order_attached', 'order_id,goods_id,title,thumb_img,number,price,attr,rebate_percentage', 'member_order_attached.order_id = member_order.id')
            ->view('shop', 'member_id as user_id,title as shop_title', 'shop.member_id = member_order.shop_id')
            ->where(['member_id' => $memberId])
            ->order(['create_time' => 'desc'])
            ->paginate(10, false);


        return $this->fetch('', [
            'mate_head' => '申请退款',
            'order'     => $order,
            'result'    => $result,
        ]);

    }


    /*
     * 申请退货请求
     */
    public function return_cargo()
    {
        // 获取参数
        $order_id = Request::instance()->param('order');

        $model = new MemberOrderModel();
        $memberId = Session::get('member_id');

        $find = $model->where('id', $order_id)->find();

        if (Request::instance()->isPost()) {
            // 获取参数
            $data = Request::instance()->param();

            // 退款传图
            $data['picArr'] = Request::instance()->param('picArr/a', '');
            if ($data['picArr']) {
                $data['picArr'] = array_map(function ($item) {
                    $item = ['path' => $item];
                    return $item;
                }, $data['picArr']);
            }

            $data['order_number'] = $find['shop_order_number'];

            if (empty(Session::get('member_id')) || empty($data['order_id'])) throw new Exception('not Empty');

            Db::startTrans();

            try {
                $find = (new MemberRefundModel())->where(['member_id' => Session::get('member_id'), 'id' => $data['order_id']])->value('id');

                if (!empty($find)) return ['code' => 402, 'message' => '该订单已经申请退款,请勿重复申请'];

                if (!empty($data['picArr'])) $data['picArr'] = serialize($data['picArr']);
                $data['member_id'] = $memberId;
                $data['create_time'] = time();
                (new MemberRefundModel())->allowField(true)->save($data);
                $model->save(['status' => '7', 'way' => '退货'], ['id' => $order_id]);

                Db::commit();

                return ['code' => 200, 'message' => '退换货申请成功,等待审核...',];


            } catch (\Exception $e) {
                halt($e->getMessage());
                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙'];
            }


        }


        return $this->fetch('', [
            'mate_head' => '申请退货',
            'order'     => $find
        ]);
    }


    /**
     * 申请订单退货
     */
    public function return_good()
    {

        if (Request::instance()->isPost()) {
            // 实例化
            $memberOrder = new MemberOrderModel();
            $memberId = Session::get('member_id');
            // 获取参数
            $data = Request::instance()->post();

            $data['member_id'] = $memberId;
            $data['create_time'] = time();
            // 退款传图
            $data['picArr'] = Request::instance()->param('picArr/a', '');

            if ($data['picArr']) {
                $data['picArr'] = array_map(function ($item) {
                    $item = ['path' => $item];
                    return $item;
                }, $data['picArr']);
            }

            $data['order_number'] = $memberOrder->where('id', $data['order_id'])->value('shop_order_number');

            if (empty(Session::get('member_id')) || empty($data['order_id'])) throw new Exception('not Empty');

            $model = new MemberRefundModel();

            $find = $model->where(['member_id' => Session::get('member_id'), 'id' => $data['order_id']])->value('id');

            if (!empty($find)) return ['code' => 402, 'message' => '该订单已经申请退款,请勿重复申请'];

            if (!empty($data['picArr'])) $data['picArr'] = serialize($data['picArr']);

            //增加会员退货记录
            $result = $model->allowField(true)->save($data);

            if ($result) {

                // 更改状态
                $memberOrder->where(['id' => $data['order_id']])->update(['status' => '6', 'way' => '退款']);

                return ['code' => 200, 'message' => '退换货申请成功,等待审核...',];
            }

            return ['code' => 401, 'message' => '网络繁忙'];
        }
    }


    public function return_express()
    {

        $id = Request::instance()->param('order');
        $order_number = MemberOrderModel::get($id);

        $find = MemberRefundModel::where('order_number',$order_number['shop_order_number'])->value('id');

        if (Request::instance()->isPost()) {

            // 获取参数
            $data = Request::instance()->param();

            // $address = (new MemberRefundModel())->where('id',$find)->value('tracking');

            // if (!empty($address)) return ['code' => 401,'message'=>'您已经填写了物流信息'];

            Db::startTrans();
            try {
                $ini = [
                    'tracking'        => $data['tracking'],
                    'tracking_number' => $data['tracking_number'],
                ];

                (new MemberRefundModel())->save(['tracking' => $data['tracking'], 'tracking_number' => $data['tracking_number']],['id'=>$find]);

                // Db::name('member_refund')->where('id', 408)->update();

                Db::name('member_order')->where('order_number', $find['order_number'])->update(['status' => 9]);
                // 提交事务

                Db::commit();

                return ['code' => 200];


            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙'];
            }
        }


        return $this->fetch('', [
            'mate_head' => '退货填写物流信息',
            'order'     => $find
        ]);
    }


    /**
     * 图片上传
     */
    public function uploadImg()
    {
        $file = request()->file('file');

        if (!empty($file)) {

            // 移动到框架应用根目录/public/uploads/ 目录下
            $upload = $file->move(ROOT_PATH . 'public' . DS . 'uploads');

            if ($upload) {

                //返回图片地址
                return Response::create(['picUrl' => 'uploads/' . date('Ymd') . '/' . $upload->getFilename()], 'json', 200);
            }

            return $file->getError();
        }

    }


    /*
    * 图片删除
    * @param string $img 图片名称
    */
    public function uploadImgDestroy()
    {
        $picUrl = Request::instance()->param('picUrl');

        if (!empty($picUrl)) {

            unlink($picUrl);
            return ['code' => 200, 'message' => '取消成功'];

        }

        return ['code' => 400, 'message' => '网络繁忙'];
    }


    public function refend()
    {
        $order_number = Request::instance()->param('order');

        $item = (new MemberRefundModel())->where('order_number',$order_number)->value('message');


        return $this->fetch('',[
           'item' => $item
        ]);
    }


}